<%@ page import="java.util.*,java.net.URLEncoder"%>
<%@ page import="net.sourceforge.wurfl.core.*" %>
<%@ page import="wap.rockvilletech.portal.*" %>
<%@ page import="wap.rockvilletech.util.StringUtils" %>
<%@ page import="org.apache.log4j.Logger" %>
<%! static final Logger log = Logger.getLogger("DOWNLOAD.JSP");%>
<%
try {
	String context = getServletContext().getContextPath();
    String entry = request.getParameter("entry") != null ? request.getParameter("entry") : "";
    if(entry.isEmpty()){
        log.warn("entry is Empty");
    	return;
    }
	String seqid = StringUtils.decryptString(entry, SystemProperty.getProperty("msisdn_encrypt_key"));
    if(seqid.isEmpty()){
        log.warn("seqid- User Trying with Invalid entry.");
    	return;
    }
	
    WURFLHolder wurflHolder = (WURFLHolder) getServletContext().getAttribute("net.sourceforge.wurfl.core.WURFLHolder");
	WURFLManager wurfl = wurflHolder.getWURFLManager();
	Device device = wurfl.getDeviceForRequest(request);    		
    WapPortalBean wpb = new WapPortalBean(device);

    String[] logPriceRecord = wpb.getContentChargingRecord(seqid);	
    if(logPriceRecord == null || logPriceRecord.length != 6) {
    	log.warn("UN-AUTHORIZED ACCESS TO DOWNLOAD CONTENT, seqid="+seqid+",entry="+entry);
    	return;
    }

    String contentId = logPriceRecord[0];
    String categoryId = logPriceRecord[1];
    String contentType = logPriceRecord[2];
    String price = logPriceRecord[3];
    String shortcode = logPriceRecord[4];
    String msisdn = logPriceRecord[5];
    
    String brand = device.getCapability("brand_name");
    String model = device.getCapability("model_name");

    Vector vec = wpb.getContentDownloadParams(contentId, categoryId, contentType, msisdn);
    if (vec.size() > 0) {
    	String dloadUrl = context+"/downloader?brand="+URLEncoder.encode(brand,"UTF-8")+"&model="+URLEncoder.encode(model,"UTF-8")+"&msisdn="+msisdn+"&logid="+seqid;
        for (int i = 0; i < vec.size(); i++) {
            String name = vec.get(i++).toString();
            String value = vec.get(i).toString();
            dloadUrl = dloadUrl+"&"+name+"="+value;
        }
        log.info("Download link validated, now redirecting to ("+dloadUrl+") for content download");
        response.sendRedirect(dloadUrl);
        return;
    }
    else {
    	%>
    	<div>Error processing your request, <a href="<%=context%>/content/dload.jsp?cid=<%=contentId%>">Click here</a> to return.</div>
    	<%
    	//wpb.setContentDownloadStatus(seqid, price, request.getRemoteHost(), brand, model);
    }
    
} catch (Exception exc) {
    log.error("Exception downlaods ", exc);
}
%>
